package util

import (
	"context"
	"fmt"
	"github.com/chromedp/cdproto/network"
	"github.com/chromedp/chromedp"
	"mp3/entity"
	"strings"
)

func SwitchChromedpTag1(config entity.DownloadEntity, url string, allocCtx context.Context) ([]string, map[string]map[string]string, map[string]string, []*network.Cookie) {
	var bodyStr string
	var length float64

	var headURLMap = make(map[string]map[string]string)
	var cookies []*network.Cookie
	var urlMap = make(map[network.RequestID]string)
	var urlHeadMap = make(map[string]string)
	var urls []string

	if IsNotEmpty(config.NextClickTag) {
		responseEntity, _, _ := switchPlayList(url, entity.DownloadEntity{}, allocCtx)
		valURL := playClick(responseEntity.Document, config)
		if IsNotEmpty(valURL) {
			url = valURL
		}
	}

	allocCtx, cancel := CreateAllocCtx()
	ctx, cancel1 := chromedp.NewContext(allocCtx)
	defer cancel1()
	defer cancel()

	chromedp.ListenTarget(ctx, func(ev interface{}) {
		switch evn := ev.(type) {
		case *network.EventRequestWillBeSent:
			if len(config.AudioTypes) > 0 {
				for _, audioType := range config.AudioTypes {
					headMap := chooseHead(evn.Request.Headers)
					headURLMap[evn.Request.URL] = headMap

					if strings.Index(strings.ToLower(evn.Request.URL), strings.ToLower(audioType)) > 0 {
						if strings.Index(evn.Request.URL, "url=") == -1 {
							urlMap[evn.RequestID] = evn.Request.URL
							urls = append(urls, evn.Request.URL)
						}
					}

					if strings.Index(strings.ToLower(evn.Request.URL), strings.ToLower(audioType)) > 0 {
						urls = append(urls, evn.Request.URL)
					}
				}
			}
		case *network.EventResponseReceivedExtraInfo:

		case *network.EventLoadingFinished:
		case *network.EventResponseReceived:
			resp := evn.Response
			if len(resp.Headers) != 0 {
				for key, value := range resp.Headers {
					if !ContainsStr(HEADERS, key) {
						urlHeadMap[key] = fmt.Sprintf("%s", value)
					}
				}

			}

		}
	})

	var err error

	if IsNotEmpty(config.ChildClickTag) {

		chromedp.Run(ctx,
			chromedp.Navigate(url),
			chromedp.Sleep(Sleep_Value),
			chromedp.OuterHTML(`body`, &bodyStr, chromedp.ByQuery),
			chromedp.Click(config.ChildClickTag),
			chromedp.ActionFunc(func(ctx context.Context) error {
				cookies, err = network.GetCookies().Do(ctx)
				return err
			}),
		)
	} else {
		chromedp.Run(ctx,
			chromedp.Navigate(url),
			chromedp.Sleep(Sleep_Value),
			chromedp.OuterHTML(`body`, &bodyStr, chromedp.ByQuery),
			chromedp.ActionFunc(func(ctx context.Context) error {
				cookies, err = network.GetCookies().Do(ctx)
				if err != nil {
					return err
				}

				return err

			}),
		)
		for i := 0; i < Default_Sleep_Value; i++ {
			if length > 0 {
				break
			}
			SleepTime(1)
		}

	}

	return urls, headURLMap, urlHeadMap, cookies
}

// 加载Cookies
func chooseHead(head network.Headers) map[string]string {
	headMap := make(map[string]string)
	length := len(head)
	if length > 0 {
		for key, value := range head {
			valueStr := fmt.Sprintf("%s", value)
			//if util.IsNotEmpty(valueStr) {
			headMap[key] = valueStr
			//}

		}
	}

	return headMap
}

func switchM3u8URL(requestIdOfM3u8 network.RequestID, requestIds []network.RequestID, urlMap map[network.RequestID]string,
	lengthMap map[float64]network.RequestID, length float64, config entity.DownloadEntity) string {
	var m3u8 string
	if len(requestIds) == 1 {
		return urlMap[requestIdOfM3u8]
	}
	if len(requestIds) > 1 && !IsEmpty(config.SourceMp3) {
		return switchM3u8URLOfSourceMap3(config, urlMap)
	}

	if len(requestIds) == 0 {
		m3u8 = urlMap[lengthMap[length]]
		if len(urlMap) == 1 {
			m3u8 = urlMap[requestIdOfM3u8]
		} else {
			if IsEmpty(config.SourceMp3) {
				for key := range lengthMap {
					delete(urlMap, lengthMap[key])
				}

				if len(urlMap) == 1 {
					for urlKey := range urlMap {
						m3u8 = urlMap[urlKey]
						break
					}
				}
			}
			return switchM3u8URLOfSourceMap3(config, urlMap)
		}
	}

	if IsEmpty(m3u8) {
		for urlKey := range urlMap {
			m3u8 = urlMap[urlKey]
		}
	}
	return m3u8
}

func switchM3u8URLOfSourceMap3(config entity.DownloadEntity, urlMap map[network.RequestID]string) string {
	if IsNotEmpty(config.SourceMp3) {
		for urlKey := range urlMap {
			if strings.Index(strings.TrimSpace(urlMap[urlKey]), strings.TrimSpace(config.SourceMp3)) > -1 {
				return urlMap[urlKey]
			}
		}
	}

	m3u8 := ""
	for urlKey := range urlMap {
		m3u8 = urlMap[urlKey]
	}

	return m3u8
}
